package com.jt.demos;

import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class CartDemo01{

 public static void addCart(Long userId,Long productId,int num){
  Set<HostAndPort> nodes=new HashSet<>();
  nodes.add(new HostAndPort("192.168.126.129",8010));
  nodes.add(new HostAndPort("192.168.126.129",8011));
  nodes.add(new HostAndPort("192.168.126.129",8012));
  nodes.add(new HostAndPort("192.168.126.129",8013));
  nodes.add(new HostAndPort("192.168.126.129",8014));
  nodes.add(new HostAndPort("192.168.126.129",8015));

  JedisCluster jedisCluster=new JedisCluster(nodes);
  String product=jedisCluster.hget("cart:"+userId,String.valueOf(productId));
  System.out.println(product);
  if(product!=null){
   jedisCluster.hincrBy("cart:"+userId,String.valueOf(productId),num);
  }else{
   jedisCluster.hset("cart:"+userId,String.valueOf(productId),String.valueOf(num));
  }
  jedisCluster.close();
 }

 public static Map<String,String> listCart(Long userId){
  Set<HostAndPort> nodes=new HashSet<>();
  nodes.add(new HostAndPort("192.168.126.129",8010));
  nodes.add(new HostAndPort("192.168.126.129",8011));
  nodes.add(new HostAndPort("192.168.126.129",8012));
  nodes.add(new HostAndPort("192.168.126.129",8013));
  nodes.add(new HostAndPort("192.168.126.129",8014));
  nodes.add(new HostAndPort("192.168.126.129",8015));

  JedisCluster jedisCluster=new JedisCluster(nodes);
  Map<String,String> map=jedisCluster.hgetAll("cart:"+userId);
  jedisCluster.close();
  return map;
 }

 public static void main(String[] args){
  addCart(101L,201L,1);
  addCart(101L,202L,1);
  addCart(101L,203L,2);
  Map<String,String> map=listCart(101L);
  System.out.println(map);
 }
}
